// Copyright (C) 2011 YANG Hao (yangh2007@gmail.com). All rights reserved.
//
// This file is part of the (cute)octopus project.
//
// This file may be distributed and/or modified under the terms of the
// GNU General Public License version 2 as published by the Free Software
// Foundation.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
//
// Author(s): YANG Hao


#include "odoc.h"

#include "oevent.h"
#include "ocreator.h"
#include "owindow.h"
#include "odescriptors.h"

ODoc::ODoc(const QString& path, const QIcon& icon,  QObject *parent)
: QObject(parent), m_readOnly(false), m_fileInfo(path), m_icon(icon)
{
	m_waitingForWidgetUpdate = false;
	m_modified = !m_fileInfo.exists();
}

bool ODoc::updateWidgets(OTaskAsync* invoker /*= 0*/)
{
	if(rel_winds.empty())
		return false;
	lock();
	if(!m_waitingForWidgetUpdate){
		foreach(OWindow* w, rel_winds){
			OEvent* message = new OEvent(OStd::Event_WidgetUpdate);
			message->setSender(invoker);
			QCoreApplication::postEvent((QObject*)(w->widget()), message, Qt::HighEventPriority + 1);
		}
		m_waitingForWidgetUpdate = true;
	}
	unlock();
	return true;
}

void ODoc::setModified(bool m){
	if(m != m_modified){
		m_modified = m;
		updateWidgets();
	}
}

void ODoc::setReadOnly(bool r){
	if(m_readOnly != r){
		m_readOnly = r;
		updateWidgets();
	}
}

void ODoc::setResource(const QString& filePath)
{
	m_fileInfo = QFileInfo(filePath);
	foreach(OWindow* w, rel_winds)
		w->updateFilePath();
}

ODocList oRequireDocs(ODoc* current, const QStringList& newDocDescriptors)
{
	ODocList retDocs;
	retDocs << current;
	for(int i = 0; i < newDocDescriptors.size(); i++){
		ODoc* doc = oApp()->openDoc(current->fileInfo().path() 
			+ current->fileInfo().baseName() + newDocDescriptors.at(i) 
			+ current->suffix());
		retDocs << doc;
	}
	return retDocs;
}